(function($) {
	/*
	* Do responsive style stuff when DOM is ready
	*/
	$(document).ready(function() 
	{
		var counter = 0,
			menuButtonHTML = '',
			oldIE = false;
	
		// Browser check
		(function() 
		{
			var test = document.createElement('div'),
				userAgent = (navigator) ? navigator.userAgent : '';

			if (typeof test.style.borderRadius == 'undefined')
			{
				oldIE = true;
				$('html').addClass('OldIE');
			}
			else if (typeof test.style.msTransform == 'string' && typeof test.style.msTransition == 'undefined')
			{
				IE9 = true;
			}

			delete test;
		}) ();
		
		// Page sidebar
		if ($('.responsiveSidebarToggle').addClass('hasJs').length)
		{
			$('.sidebar').parent('aside').addClass('responsiveSidebarContainer');
			$('.responsiveSidebarToggle .callToAction').addClass('responsiveSidebarCallToAction').click(function() {
				var $body = $('body');
				$body.toggleClass('responsiveSidebarVisible');
				$('strong.small-arrow', this).html($body.hasClass('responsiveSidebarVisible') ? '&uarr;' : '&darr;');
			}).find('span').append('<strong class="small-arrow">&darr;</strong>');
		}

		// Navigation
		$('#responsiveNavigation').each(function()
		{
			var $this = $(this),
				prev = $(this).parent(),
				navigation = $(this).parents('#navigation'),
				tabs = navigation.find('.navTabs');

			tabs.after('<div class="navTabs responsiveNavTabs" style="display: none;"><ul></ul></div>');

			var container = navigation.find('.responsiveNavTabs ul'),
				found = false;
			
			tabs.find('ul > li.navTab').each(function()
			{
				container.append($(this).clone(false));
				found = true;
			});
			
			if (!found)
			{
				container.remove();
				return;
			}
			
			var extraLinks = '';
			container.find('.navTab.selected .tabLinks .blockLinksList li a[href]').each(function()
			{
				var $this = $(this);
				extraLinks += '<li class="navTab"><a class="navLink" href="' + $this.attr('href') + '">' + $this.text() + '</a></li>';
			});
			if (extraLinks != '')
			{
				container.after('<ul class="responsiveNavigationExtra">' + extraLinks + '</ul>');
			}

			container.find('li').removeClass('PopupOpen PopupControl PopupContainerControl');
			container.find('.arrowWidget, .SplitCtrl, .tabLinks, .Menu').remove();
			container.find('[id]').attr('id', '');

			prev.addClass('responsiveNavigationContainer');

			var button = $this.find('.callToAction');
			menuButtonHTML = button.html();
			button.addClass('responsiveNavigationCallToAction').click(function() {
				prev.toggleClass('responsiveNavigationVisible');
				$('strong.small-arrow', this).html(prev.hasClass('responsiveNavigationVisible') ? '&uarr;' : '&darr;');
			}).find('span').append('<strong class="small-arrow">&darr;</strong>');
			
			// Add counters
			var counters = '';
			tabs.find('a[href] .itemCount[data-text]').each(function()
			{
				var $this = $(this),
					total = $this.find('.Total').text();

				if (!total.length || total == '0')
				{
					return;
				}

				counters += '<li><a href="' + $(this).closest('a[href]').attr('href') + '">' + $(this).data('text').replace('%d', total) + '</a></li>';
			});
			if (counters != '')
			{
				$('.pageContent .breadBoxTop').before('<div class="responsiveExtraAlerts" style="display: none;"><ul>' + counters + '</ul></div>');
			}
		});
		
		// Swap button and navigation in breadcrumbs
		$('.breadBoxTop > .topCtrl').each(function() {
			var $this = $(this),
				nav = $this.next('nav');
				
			if ($this.hasClass('responsiveHide') || $this.hasClass('responsiveShow') || !nav.length)
			{
				return;
			}
			
			nav.after($this.clone());
			$this.addClass('responsiveHide');
			nav.next('.topCtrl').css('display', 'none').addClass('responsiveShow');
		});
		
		// Breadcrumbs
		$('.breadcrumb[data-limit]').each(function()
		{
			var $this = $(this),
				limit = parseInt($this.data('limit'));
				
			if (isNaN(limit) || limit < 2)
			{
				return;
			}
			
			var items = $this.find('.crust'),
				total = items.length;

			if (total <= limit)
			{
				return;
			}
			
			for (var i=0; i < (total - limit); i++)
			{
				items.eq(i + 1).addClass('responsiveHide');
			}
		});

		$('.breadcrumb .crumbs').each(function()
		{
			var $this = $(this),
				counter = $this.find('.crust').not('.responsiveHide').length;
			
			for (var i=1; i<=counter; i++)
			{
				$this.addClass('split-' + i);
			}
		});
		
		// Header
		$('#headerProxy + div > div.pageWidth').parent().addClass('hasPageWidth');
		
		// Account/help sidebars
		$('.accountSideBar .section, .helpSideBar .section').each(function()
		{
			var $this = $(this),
				heading = $this.find('.heading, .subHeading');
			if (heading.length != 1 || heading.closest('a').length > 0)
			{
				return;
			}
			
			var content = heading.next();
			if (content.length != 1 || content.get(0).tagName.toUpperCase() != 'UL')
			{
				return;
			}
			
			var visible = (content.find('a.secondaryContent').length > 0);

			content.addClass('responsiveHide' + (visible ? ' responsiveShow' : ''));
			heading.addClass('responsiveClickable' + (visible ? ' menuVisible' : ' menuHidden')).append('<strong class="small-arrow" style="display: none;">' + (visible ? '&uarr;' : '&darr;') + '</strong>').click(function() 
			{ 
				content.toggleClass('responsiveShow');
				heading.toggleClass('menuVisible menuHidden');
				$('strong.small-arrow', this).html(content.hasClass('responsiveShow') ? '&uarr;' : '&darr;');
			});
		});
		
		// Profile page sidebar
		counter = 0;
		$('.profilePage .mast').each(function()
		{
			if (menuButtonHTML == '')
			{
				return;
			}

			var $this = $(this).addClass('responsiveSideHide'),
				num = counter;

			counter ++;
			$this.before('<div class="responsiveMastButton responsiveSideShow" style="display: none;" id="responsiveMast' + num + '"><a class="callToAction responsiveProfileCallToAction"></a></div>');
			var button = $('#responsiveMast' + num + ' a').html(menuButtonHTML);
			
			var span = button.find('span[data-lang-sidebar]');
			if (span.length)
			{
				span.html(span.attr('data-lang-sidebar'));
			}
			
			button.click(function() 
			{ 
				$this.toggleClass('responsiveSideShow');
				button.find('strong.small-arrow').html($this.hasClass('responsiveSideShow') ? '&uarr;' : '&darr;');
			}).find('span').append('<strong class="small-arrow">&darr;</strong>');
		});
		
		// Hide header elements other than logo
		$('#header .pageContent').each(function()
		{
			var $this = $(this),
				logo = $this.children('#logo'),
				children = $this.children().not('#logo, .helper');
			if (!logo.length || !children.length)
			{
				return;
			}
			children.addClass('responsiveHide');
		});
		
		// Moderator bar
		$('#moderatorBar .itemLabel, #header_bar .itemLabel').each(function()
		{
			var $this = $(this);
			$this.attr('title', $this.text());
		});
		
		// Resource manager sidebar
		$('.resourceListSidebar').each(function() {
			var $this = $(this),
				shown = false,
				text = $this.attr('data-title');

			if (!text)
			{
				text = $('.titleBar h1').text();
			}

			$this.css('display', 'block').children().addClass('resourceListSidebarInner');
			$this.prepend('<div class="resourceListSidebarToggle" style="display: none;"><a class="callToAction" href="javascript:void(0);"><span>' + text + ' <strong>&darr;</strong></span></a></div>')
			$('.titleBar').addClass('hidden');

			var button = $this.find('.callToAction');

			button.click(function() {
				shown = !shown;
				button.find('strong').html((shown) ? '&uarr;' : '&darr;');
				$this.toggleClass('sidebarVisible', shown);
			});
		});

		// Clickable rows
		$('.discussionListItem .main, .nodeList .nodeInfo').click(function(event)
		{
			// Check resolution
			if ($(window).width() > 700)
			{
				return;
			}
			
			// Find all links
			var $this = $(this),
				target = $(this).find('.title a[href], .nodeTitle a[href]').not('.unreadLink'),
				links = $this.find('a, input').not('.posterDate a:not(.itemPageNav a)').not(target);

			function doClick()
			{
				// document.location.href = target.attr('href');
				var link = target.attr('href');
				if (link.indexOf('://') >=0 || link.indexOf('/') == 0)
				{
					// absolute/external link
					document.location.href = link;
				}
				else
				{
					var base = $('base');
					if (base.length != 1)
					{
						document.location.href = link;
					}
					else
					{
						link = base.attr('href') + link;
						document.location.href = link;
					}
				}
				event.preventDefault();
				return true;
			}
			
			function getOffset(obj) 
			{
				var obj2 = obj,
					curtop = 0;
					curleft = 0;
				if (document.getElementById || document.all) 
				{
					do
					{
						curleft += obj.offsetLeft - obj.scrollLeft;
						curtop += obj.offsetTop - obj.scrollTop;
						obj = obj.offsetParent;
						obj2 = obj2.parentNode;
						while (obj2 != obj) 
						{
							curleft -= obj2.scrollLeft;
							curtop -= obj2.scrollTop;
							obj2 = obj2.parentNode;
						}
					}
					while (obj.offsetParent);
				} 
				else if (document.layers)
				{
					curtop += obj.y;
					curleft += obj.x;
				}
				return {top: curtop, left: curleft};
			} 

			if (target.length != 1 || (links.length == 0) && doClick())
			{
				return;
			}
			
			// Calculate coordinates
			var diff = 30,
				x = event.pageX,
				y = event.pageY,
				match = false;

			if (!x || !y) return;
			
			links.each(function() 
			{
				if (match) return;

				var item = $(this);
				if (!item.is(':visible'))
				{
					// hidden item
					return;
				}
				
				var offset = getOffset(this);
					
				if (offset.left > (x + diff) || offset.top > (y + diff))
				{
					// to left or above link
					return;
				}
				
				if ((offset.left + item.width()) < (x - diff) || (offset.top + item.height()) < (y - diff))
				{
					// to right or below link
					return;
				}
				
				match = true;
			});
			
			if (!match)
			{
				doClick();
			}
		});
	});
})(jQuery);